package com.nm.service.impl;

import com.nm.commons.exception.ErrorsDispatcher;
import com.nm.commons.exception.SupperException;
import com.nm.commons.util.StringUtil;
import com.nm.orm.model.State;
import com.nm.orm.dao.MenuDao;
import com.nm.orm.pojo.MenuEntity;
import com.nm.service.MenuService;
import com.nm.service.output.MenuEasy;
import com.nm.utils.AssertSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by hewu on 2017/2/8 0008.
 */
@Service
@Transactional
@Qualifier("menusService")
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public String insert(MenuEntity menuEntity) {
        return menuDao.insert(menuEntity);
    }

    @Override
    public void saveOrUpdate(MenuEntity menu) {
        if (StringUtil.isNull(menu.getId())) {
            menu.setCreatedAt(new Date());
        }

        if (State.DISABLE.dbValue() == menu.getState()) {
            menu.setState(State.ABLE.dbValue());
        }
        menuDao.saveOrUpdate(menu);
    }

    @Override
    public void update(MenuEntity menu) {
        menu.setUpdatedAt(new Date());
        if ("".equals(menu.getId())){
            menu.setId(null);
        }
        if (State.DISABLE.dbValue() == menu.getState()) {
            menu.setState(State.ABLE.dbValue());
        }

        menuDao.saveOrUpdate(menu);
    }

    @Override
    public MenuEntity getById(String id) {
        return menuDao.findById(id);
    }

    @Override
    public void delete(MenuEntity menuEntity) {

        menuDao.delete(menuEntity);
    }

    @Override
    public int deleteById(String id) {
        return menuDao.deleteById(id);
    }

    @Override
    public List<MenuEasy> findAll() throws SupperException {

        List<MenuEntity> menus = menuDao.findAll();
        AssertSupport.isNullList(menus, ErrorsDispatcher.FailAddMenu);

        List<MenuEasy> menuEasies = new ArrayList<MenuEasy>();

        MenuEasy easy = null;
        for (int i = 0; i < menus.size(); i++) {
            MenuEntity menu = menus.get(i);

            easy = new MenuEasy();
            easy.setId(i + 1);
            easy.setMenuId(menu.getId());
            easy.setState(menu.getState());
            easy.setText(menu.getName());
            easy.setUrl(menu.getUrl());

            menuEasies.add(easy);
        }

        return menuEasies;
    }
}